<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for=" (item1,i1) in scope.row.children" :key="item1.id"
              :class="['bdBottom', i1 === 0 ? 'bdTop':'','vcenter']">
              <!-- 一级循环 -->
              <el-col :span="5">
                <el-tag type="primary" closable @close="closeTagById(scope.row,item1.id)">{{ item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级循环 -->
              <el-col :span="19">
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2===0?'':'bdTop','vcenter']">
                  <el-col :span="8">
                    <el-tag type="success" closable @close="closeTagById(scope.row,item2.id)">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级循环 -->
                  <el-col :span="16">
                    <el-tag v-for="(item3) in item2.children" :key="item3.id" type="warning" closable
                      @close="closeTagById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分配角色对话框 -->
      <el-dialog title="分配权限" :visible.sync="SetRightDialogVisible" width="50%" @close="closeSetDialog">
        <!-- 树形控件 -->
        <el-tree :data="rightsList" :props="rightProps" show-checkbox node-key="id" default-expand-all
          :default-checked-keys="defKeys" ref="rightTreeRef">
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="SetRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitSetDialog">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      SetRightDialogVisible: false,
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      rightsList: [],
      defKeys: [],
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 渲染角色页面
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败！')
      this.rolesList = res.data;
    },
    // 点击删除时通过id删除图标
    async closeTagById (role, rightId) {

      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)

        if (res.meta.status !== 200) return this.$message.error('删除用户权限失败')

        // 会刷新页面关闭展开页面
        // this.getRolesList()

        // 重新赋值不会刷新页面
        role.children = res.data
        // console.log(role)
        // console.log(res)

        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 展示分配权限对话框
    async showSetDialog (role) {

      this.roleId = role.id
      // 获取所有权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限信息失败')
      this.rightsList = res.data
      console.log(this.rightsList)
      this.getLeafKeys(role, this.defKeys)
      this.SetRightDialogVisible = true;
    },

    // 获取默认勾选的节点的 key 的数组
    getLeafKeys (node, arr) {
      // 如果是三级节点就加入数组
      if (!node.children) {
        return arr.push(node.id)
      }
      // 通过递归寻找到三级节点
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    closeSetDialog () {
      this.defKeys = []
    },
    async submitSetDialog () {
      // 获取所有被选中的三级节点和半选中的一二级节点
      const CheckedKeys = [
        ...this.$refs.rightTreeRef.getCheckedKeys(),
        ...this.$refs.rightTreeRef.getHalfCheckedKeys()
      ]
      const keysStr = CheckedKeys.join(',')

      //获取用户权限
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keysStr })
      if (res.meta.status !== 200) return this.$message.error('获取用户权限失败')
      this.$message.success('更新用户权限成功')
      this.getRolesList()

      console.log(CheckedKeys)
      this.SetRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}

.bdBottom {
  border-bottom: 1px solid #eee;
}

.bdTop {
  border-top: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>